package com.mooc.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VCodeUtil {
    private int width;
    private int height;
    private int codeNum;
    private String codeSet = "2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY";

    private String code;
    private BufferedImage image;
    private Graphics2D drawer;
    private Random r = new Random();


    public VCodeUtil(int width, int height, int codeNum) {
        this.width = width;
        this.height = height;
        this.codeNum = codeNum;
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        this.drawer = this.image.createGraphics();
        init();
    }

    public VCodeUtil(int width, int height) {
        this(width, height, 4);
    }

    public VCodeUtil(int codeNum) {
        this(200, 40, codeNum);
    }

    public VCodeUtil() {
        this(200, 40, 4);
    }

    public BufferedImage getImage() {

        return this.image;
    }


    private void init() {
        drawer.setColor(Color.WHITE);
        drawer.fillRect(0, 0, width, height);
        drawRandomText();
    }


    private void drawRandomText() {
        String code = "";
        int len = codeSet.length();
        Font f = new Font("微软雅黑", Font.BOLD, (int) (height * 0.6));
        drawer.setFont(f);
        int perWidth = this.width / this.codeNum;
        for (int i = 0; i < codeNum; i++) {
            int x = perWidth * i + new Random().nextInt(5) + 10;
            int n = new Random().nextInt(len);
            char c = codeSet.charAt(n);
            drawer.setPaint(new Color(new Random().nextInt(220), new Random().nextInt(220), new Random().nextInt(220)));
            drawer.drawString(String.valueOf(c), x, this.height / 2 + new Random().nextInt(5) + 5);
            code += c;
        }
        drawLine();
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }


    private void drawLine() {
        int num = width / 10;// 一共画20条
//		Graphics2D g2 = (Graphics2D)image.getGraphics();
        for (int i = 0; i < num; i++) {// 生成两个点的坐标，即4个值
            int x1 = r.nextInt(width);
            int y1 = r.nextInt(height);
            int x2 = r.nextInt(width);
            int y2 = r.nextInt(height);
            drawer.setStroke(new BasicStroke(1.5F));
            drawer.setColor(Color.LIGHT_GRAY); // 干扰线是深灰色
            drawer.drawLine(x1, y1, x2, y2);// 画线
        }
    }
}
